// ////////////////////////////////////////////////////////////////////////////////////////
// NAME: ListviewActivity.java 
// AUTHOR: CDT Riley Mckenna, CDT Peter Lofreddo
// LAST MODIFIED: 28 March 2012 
// DESCRIPTION: Contains code to change applications in the listview.
// LIMITATIONS: 
// CITATIONS: In code
// 
// ////////////////////////////////////////////////////////////////////////////////////////
package prototype.revision;

import java.io.IOException;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewActivity extends ListActivity {
	private String listName = "installed_programs.txt";
	private FileOperations fo = new FileOperations(this);
	private BlockUnblockPopup pop = new BlockUnblockPopup(this, fo);
	private final String TAG = "ListViewActivity";
	private ListView lv;
	private Toast t;
	private ColorManager cm = new ColorManager();
	private int red = Color.rgb(255, 40, 45);
	private int green = Color.rgb(129, 253, 53);
	private int blue = Color.rgb(122, 158, 243);
	private final Handler my_handler = new Handler();
	private int my_sample_poll = 1000;
	private boolean running = false;
	//private Sting TAG = "ListViewActivity";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			Process root = Runtime.getRuntime().exec("su");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
      //  Log.i(TAG, "Created Activity");
        fo.ListAllInstalledPrograms();
      //  Log.i(TAG, "Returned List of allinstalled Programs...");
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, fo.ReadFileAsList(listName) ));  
        setLv(getListView());
        lv.setTextFilterEnabled(true);
        running = true;
        my_handler.postDelayed(this.mUpdate, my_sample_poll);
    }
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
        try {
			changeColor();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String item = (String) getListAdapter().getItem(position);
		//Log.d(TAG, "An item:" + item + " has been clicked...");
		pop.BlockUnblockUninstallPopUp(item);
		if (cm.checkIfInBlackList(item)) {
			//l.getSelectedItemId().setBackgroundColor(Color.RED);
			lv.getChildAt(position).setBackgroundColor(red);
			//lv.findViewById((int) id).setBackgroundColor(red);
		}
		else if (cm.checkIfInWhiteList(item)){
			lv.getChildAt(position).setBackgroundColor(green);
			//lv.findViewById((int) id).setBackgroundColor(green);
		}
		//else if (pop.isActive()== false){
		else {
			//Log.d(TAG, l.getChildAt(position) + " pos; " + l +" lv; "+ v+ " view;" + lv + " listview;");
			v.setBackgroundColor(blue); 
		}
//		Log.i(TAG, "popup complete");
	}

	public void setListName(String fileName) {
		listName = fileName;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about:
			t = Toast
					.makeText(
							getApplicationContext(),
							"Touch a loaded Application to change its firewall preferences",
							15);
			t.show();
			break;
		case R.id.settings:
			Log.i(TAG, "Starting settings tab...");
			startActivity(new Intent(this, Settings.class));
			break;
		case R.id.clear:
			Log.i(TAG, "clearing list");
			pop.clearBlackListorWhiteList();
			break;
		case R.id.exit:
			finish();
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.firewall, menu);
		return true;
	}

	public ListView getLv() {
		return lv;
	}

	public void setLv(ListView lv) {
		this.lv = lv;
	}
	public void changeColor() throws IOException	{
		IOException e = new IOException(); 
		int firstPosition = lv.getFirstVisiblePosition() - lv.getHeaderViewsCount();
		int lastPosition = lv.getLastVisiblePosition() - lv.getHeaderViewsCount();
		for (int i = firstPosition; i < lastPosition; i++) {
			//Log.d(TAG, (String) getListAdapter().getItem(i) + " to Sting " + i + " id");
			int wantedPosition = i;
			//int firstPosition = lv.getFirstVisiblePosition() - lv.getHeaderViewsCount();
			//Log.d(TAG, ""+ firstPosition + " 1st pos sting " + wantedPosition);
			int wantedChild = wantedPosition - firstPosition;
			//Log.d(TAG, ""+ wantedChild + " wanted sting ");
			String item = (String) getListAdapter().getItem(wantedPosition);
			//Log.d(TAG, ""+ item + " last visable number sting ");
			
			if (cm.checkIfInBlackList(item)) {
				lv.getChildAt(wantedChild).setBackgroundColor(red);
			} else if (cm.checkIfInWhiteList(item)) {
				lv.getChildAt(wantedChild).setBackgroundColor(green);
			}

			else if (!cm.checkIfInBlackList(item) && !cm.checkIfInWhiteList(item)) {
				lv.getChildAt(wantedChild).setBackgroundColor(blue);
			}
			else {
				throw e;
			}
		}
	}
	@Override
	public void onPause(){
		super.onPause();
		running = false;
		my_handler.removeCallbacks(mUpdate);
	}
	@Override
	public void onResume(){
		super.onResume();
		running = true;
        my_handler.postDelayed(this.mUpdate, my_sample_poll);
	}
	@Override
	public void onStop(){
		super.onStop();
		running = false;
		my_handler.removeCallbacks(mUpdate);
	}
	
	private Runnable mUpdate = new Runnable() {
		public void run() {
			if (running) {
				try {
					changeColor();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Log.i("Runnable", "PackageName" + "Refreshing.");
				my_handler.postDelayed(mUpdate, my_sample_poll);
			} else {

			}

		}

	};
}